# coding: utf-8

import os
import smtplib
import time
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import openpyxl
import requests
from openpyxl import Workbook, load_workbook
from selenium.common import NoSuchElementException, \
    ElementNotInteractableException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as Wait

from settings import LOG_DIR


def send_log(file_name: str, message: str):
    """
    日志实时传输
    :param file_name:
    :param message:
    :return:
    """
    path = os.path.join(LOG_DIR, file_name)
    with open(path, 'a', encoding="utf-8") as f:
        f.write(f'{message} \n')
    return


# 步骤1：使用Selenium获取cookies
def get_cookies_with_selenium(driver):
    return driver.get_cookies()


# 步骤2：将获取的cookies转换成requests库所需的格式
def convert_cookies(cookies):
    formatted_cookies = {}
    for cookie in cookies:
        formatted_cookies[cookie['name']] = cookie['value']
    return formatted_cookies


# 步骤3：使用requests库发送请求，并携带转换后的cookies
def make_request_with_cookies(cookies):
    url = "https://www.example.com"  # 替换为实际请求的URL
    headers = {"User-Agent": "Your User Agent"}
    response = requests.get(url, headers=headers, cookies=cookies)
    return response.text


# 用于合并多个 Excel 文件，将多个工作表中的内容整合到一个工作表中
def merge_xlsx_files(folder_path, output_file):
    merged_workbook = Workbook()
    merged_sheet = merged_workbook.active
    for filename in os.listdir(folder_path):
        if filename.endswith(".xlsx"):
            file_path = os.path.join(folder_path, filename)
            workbook = load_workbook(file_path)
            sheet = workbook.active
            for row in sheet.iter_rows(values_only=True):
                merged_sheet.append(row)
    merged_workbook.save(output_file)
    print("合并完成，输出文件路径：", output_file)


# 该方法用于将爬取到的数据追加写入到一个指定的 Excel 文件中
def write_cms_to_excel(result_file, cms_list):
    if not os.path.exists(result_file):
        workbook = Workbook()
        workbook.save(result_file)
        workbook.close()
    workbook = load_workbook(result_file)
    sheet = workbook.active
    sheet.append(cms_list)
    workbook.save(result_file)
    workbook.close()


# 注入 JavaScript 代码，获取页面中的网络请求信息
def get_network_requests(driver):
    network_requests_script = """
        var requests = window.performance.getEntriesByType('resource');
        return JSON.stringify(requests);
    """
    requests_json = driver.execute_script(network_requests_script)
    requests_list = eval(requests_json)
    return requests_list


# 方法用于发送带有附件的邮件，比如爬取结果文件
def send_email(send_file, email_address_list, out_log_file):
    return
    msg_from = '3350299857@qq.com'
    passwd = 'nblksbzvhdegdbid'
    to = email_address_list

    msg = MIMEMultipart()
    msg.attach(MIMEText("版权提示", 'plain', 'utf-8'))
    att1 = MIMEText(open(send_file, 'rb').read(), 'base64', 'utf-8')
    att1['Content-Type'] = 'application/octet-stream'
    att1.add_header('Content-Disposition', 'attachment', filename=send_file)
    msg.attach(att1)
    msg['Subject'] = "版权提示"
    msg['From'] = msg_from

    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, to, msg.as_string())
    s.quit()
    send_log(out_log_file, "邮件发送成功")


# 方法用于发送自定义的错误邮件消息
def send_email_with_message(email_address_list, message, out_log_file):
    return
    msg_from = '3350299857@qq.com'
    passwd = 'nblksbzvhdegdbid'
    to = email_address_list

    msg = MIMEMultipart()
    msg.attach(MIMEText(message, 'plain', 'utf-8'))
    msg['Subject'] = "错误提示"
    msg['From'] = msg_from

    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, to, msg.as_string())
    s.quit()
    send_log(out_log_file, "邮件发送成功")


def read_cms_list_from_excel(xlsx_file):
    # 打开Excel文件
    workbook = openpyxl.load_workbook(xlsx_file)
    # 选择工作表
    sheet = workbook.active
    # 读取数据
    tag_list = []
    for row in sheet.iter_rows(values_only=True):
        for cell in row:
            if cell is None or cell == "":
                continue
            # print(cell)
            tag_list.append(cell)
    # 关闭Excel文件
    workbook.close()
    return tag_list


def handle_asset(driver, tag, email_address_list, craw_number,
                 create_time_range, craw_result,
                 update_time_range, out_log_file_name):
    num = 1
    while True:
        try:
            FINSHED = False
            import pdb
            asset_element = Wait(driver, 60, 0.5).until(
                EC.presence_of_element_located(
                    (By.ID, "asset-metadata")))

            time.sleep(2)

            element_asset_info = asset_element.find_element(By.ID,
                                                            'global-asset-info')
            metadata_section = asset_element.find_element(By.ID,
                                                          'metadata-section')
            asset_info_section = element_asset_info.find_elements(
                By.CLASS_NAME, 'asset-info-section')

            titile, ID, create_time, update_time, owner = None, None, None, None, None

            title = asset_element.find_element(By.ID,
                                               'asset-title').text

            for i in range(len(asset_info_section)):
                element = asset_info_section[i]
                section_title = element.find_element(By.CLASS_NAME,
                                                     'section-title').text
                if section_title == "资产 ID":
                    ID = element.find_element(By.CLASS_NAME,
                                              'section-content').text
                if section_title == "创建日期":
                    create_time = element.find_element(
                        By.CLASS_NAME, 'section-content').text
                if section_title == "更新日期":
                    update_time = element.find_element(
                        By.CLASS_NAME, 'section-content').text
                if section_title == "所有权":
                    section_content = element.find_element(
                        By.CLASS_NAME, 'section-content')
                    label = section_content.find_element(
                        By.CLASS_NAME, 'label')
                    owner = label.text

            content = ""
            section_labels = metadata_section.find_elements(By.ID,
                                                            'section-label')
            for i in range(len(section_labels)):
                element = section_labels[i]
                if element.text == "资产说明":
                    content = driver.find_element(By.XPATH,
                                                  '//*[@id="metadata-section"]/ytcms-asset-metadata-editor/div/div[1]/ytcp-form-textarea[2]/div/textarea').get_attribute(
                        'value')
            print(
                f"资产ID:{ID},资产标题:{title},创建时间:{create_time}")
            print(f"更新时间:{update_time},版权:{owner}")
            print(f"资产说明:{content}")

            cms_list = [title, ID, create_time, update_time, owner,
                        content]

            if create_time_range is not None and (
                    create_time != "" and create_time is not None):

                dt_create_current_time = datetime.strptime(
                    create_time, '%Y年%m月%d日')
                dt_create_self_time = datetime.strptime(
                    create_time_range, '%Y-%m-%d')
                if dt_create_current_time < dt_create_self_time:
                    send_log(out_log_file_name, "不在选定时间范围内，继续爬取")
                    print("不在选定时间范围内，继续爬取")
                    driver.find_element(By.XPATH,
                                        '//*[@id="contentIcon"]').click()
                    time.sleep(3)
                    driver.find_element(By.XPATH,
                                        '//*[@id="delete-icon"]').click()
                    time.sleep(2)
                    write_cms_to_excel(
                        craw_result + "/" + tag + ".xlsx",
                        cms_list)
                    break

            if update_time_range is not None and (
                    update_time != "" and update_time is not None):
                dt_update_current_time = datetime.strptime(
                    update_time, '%Y年%m月%d日')
                dt_update_self_time = datetime.strptime(
                    update_time_range, '%Y-%m-%d')
                if dt_update_current_time < dt_update_self_time:
                    send_log(out_log_file_name,
                             "不在选定时间范围内，继续爬取")
                    print("不在选定时间范围内，继续爬取")
                    driver.find_element(By.XPATH,
                                        '//*[@id="contentIcon"]').click()
                    time.sleep(3)
                    driver.find_element(By.XPATH,
                                        '//*[@id="delete-icon"]').click()
                    time.sleep(2)
                    write_cms_to_excel(
                        craw_result + "/" + tag + ".xlsx",
                        cms_list)
                    break

            takedown_list = read_cms_list_from_excel(
                "takdown_list.xlsx")
            print(takedown_list)
            TAKE_DOWN = True
            for cm_list in takedown_list:
                if ID in cm_list:
                    TAKE_DOWN = False
                    break

            if "takedown" in content and TAKE_DOWN == True:
                SEND_MAIL = True
                write_cms_to_excel("takdown_list.xlsx",
                                   cms_list)
            send_log(out_log_file_name,
                     f"资产ID:{ID},资产标题:{title},创建时间:{create_time}")
            send_log(out_log_file_name,
                     f"更新时间:{update_time},版权:{owner}")
            send_log(out_log_file_name, f"资产说明:{content}")
            time.sleep(2)
            next_button = driver.find_element(By.XPATH,
                                              '//*[@id="next-button"]')
            # 获取 aria-disabled 属性的值
            aria_disabled = next_button.get_attribute(
                "aria-disabled")
            write_cms_to_excel(
                craw_result + "/" + tag + ".xlsx", cms_list)

            # 判断属性值
            if aria_disabled == "true":
                print("next-button 已禁用")
                driver.find_element(By.XPATH,
                                    '//*[@id="contentIcon"]').click()
                time.sleep(3)
                driver.find_element(By.XPATH,
                                    '//*[@id="delete-icon"]').click()
                time.sleep(2)
                break
            else:
                print("next-button 可用")
                next_button.click()
            time.sleep(3)

            num += 1
            if craw_number is not None:
                if num > craw_number:
                    driver.find_element(By.XPATH,
                                        '//*[@id="contentIcon"]').click()
                    time.sleep(3)
                    driver.find_element(By.XPATH,
                                        '//*[@id="delete-icon"]').click()
                    time.sleep(2)
                    break

        except NoSuchElementException or ElementNotInteractableException:

            print("NoSuchElementException")
            send_log(out_log_file_name,
                     "ElementNotInteractableException")
            next_button = driver.find_element(By.XPATH,
                                              '//*[@id="next-button"]')
            aria_disabled = next_button.get_attribute(
                "aria-disabled")
            # 判断属性值
            if aria_disabled == "true":
                print("next-button 已禁用")
                driver.find_element(By.XPATH,
                                    '//*[@id="contentIcon"]').click()
                time.sleep(3)
                driver.find_element(By.XPATH,
                                    '//*[@id="delete-icon"]').click()
                time.sleep(2)
                break
            else:
                print("next-button 可用")
                next_button.click()
            continue

    #if SEND_MAIL == True:
    #    send_email(
    #        craw_result + "/" + tag + ".xlsx", email_address_list,
    #        out_log_file_name)
    return craw_result
